package com.mushiengine.core {
import com.mushiengine.collection.HashMap;
import com.mushiengine.collection.IMap;

import flash.utils.getDefinitionByName;

import nl.demonsters.debugger.MonsterDebugger;

public class BeanLoader implements IBeanLoader{

    private var _beanInstanceMap:IMap;
    private var _injector:IInjector;

    public function BeanLoader(instanceMap:IMap = null, injector:IInjector = null) {
        if (instanceMap == null){
            _beanInstanceMap = new HashMap(false);
        }else{
            _beanInstanceMap = instanceMap;
        }
        if (injector == null){
            _injector = new Injector();
        }else{
            _injector = injector;
        }
    }

    public function loadBeanDefinition(beanDef:IBeanDefinitionLoader):void {
        createdBeanInstances(beanDef.getDescriptions());
    }

    internal function createdBeanInstances(beanDefinition:IMap):void {

        var obj:Object;
        MonsterDebugger.trace(this,"create bean instance called");
        for each(var key:String in beanDefinition.getKeys()) {
            MonsterDebugger.trace(this,"bean: " + key);
            obj = _injector.injectViaClass(getDefinitionByName(beanDefinition.getValue(key)) as Class);
            _beanInstanceMap.put(key, obj);
        }
    }

    public function addbean(key:String, objectInst:*):void {
         var injectedObj:* = _injector.injectViaInstance(objectInst);
        _beanInstanceMap.put(key, injectedObj);
    }

    public function getBean(beanId:String):* {
        return _beanInstanceMap.getValue(beanId);
    }

    public function removeBean(beanId:String):void {
        _beanInstanceMap.remove(beanId);
    }
}
}